﻿using MoviesRoom.Data;
using MoviesRoom.Models;
using System.Net;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;

namespace MoviesRoom.Controllers
{
    [Authorize]
    public class CommentController : BaseController
    {
        public CommentController() : base(new UowData())
        {
        }

        public CommentController(IUowData data) : base(data)
        {
        }

        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Comment comment = this.Data.Comments.GetById(id.GetValueOrDefault());

            if (comment == null)
            {
                return HttpNotFound();
            }

            if (comment.User.UserName == User.Identity.Name || User.IsInRole("admin"))
            {
                return View(comment);
            }
            else
            {
                return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Comment comment)
        {
          
            if (ModelState.IsValid && (comment.UserId == User.Identity.GetUserId() || User.IsInRole("admin")))
            {
                this.Data.Comments.Update(comment);
                this.Data.SaveChanges();
                return RedirectToAction("SingleFilm", "Home", new { id = comment.FilmId });
            }

            return View(comment);
        }

        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Comment comment = this.Data.Comments.GetById(id.GetValueOrDefault());

            if (comment == null)
            {
                return HttpNotFound();
            }

            if (comment.User.UserName == User.Identity.Name || User.IsInRole("admin"))
            {
                return View(comment);
            }
            else
            {
                return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Comment comment = this.Data.Comments.GetById(id);
           
            if (comment.User.UserName == User.Identity.Name || User.IsInRole("admin"))
            {
                this.Data.Comments.Delete(comment);
                this.Data.SaveChanges();
                return RedirectToAction("SingleFilm", "Home", new { id = comment.FilmId });
            }
            else
            {
                return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }
        }
    }
}